#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

class Transform{
public:
    Transform(){
    }
    void split_line(const string& line,string & rule,string & rep){
        //cout << "line:"<< line << endl;
        int pos = line.find(' ',0);
        rule = line.substr(0,pos);
        rep = line.substr(pos+1); //文件中有两个空格
    }

    void generate_rules(const string & pathname){
        ifstream ifs(pathname);
        string line;
        while(getline(ifs,line)){
            if(line.size() > 1){
                string rule;
                string rep;
                split_line(line,rule,rep);
                _rules[rule] = rep;
            }
        }
    }
    void trans_to_target(const string & pathname1,const string & pathname2){
        ifstream ifs_source(pathname1);
        ofstream ofs_target(pathname2);
        string line;
        while(getline(ifs_source,line)){ //读出一行，转换后直接写入目标文件
            istringstream iss(line);
            string word;
            string target_line;
            while(iss >> word){
                if(_rules.find(word) != _rules.end()){
                    target_line += _rules[word] + ' ';
                }else{
                    target_line += word + ' ';
                }

            }

            if(target_line.size() > 0){
                //cout << "line:" << line << endl;
                cout << "target_line:" << target_line << endl;
                ofs_target << target_line << endl;

            }
        }
    }
    void display(){
        for(auto i : _rules){
            cout << i.first << " " << i.second << endl;
        }
    }
private:
    map<string,string> _rules;
};


void test(){
    Transform trans;
    trans.generate_rules("map.txt");
    //trans.display();
    trans.trans_to_target("file.txt","target.txt");
}

int main()
{
    test ();
    return 0;
}

